package admin

import (
	"beegoProject/models"
	"beegoProject/utils/errmsg"
	"encoding/json"
	"github.com/astaxie/beego"
)

type CategoryController struct {
	beego.Controller
}


//添加分类
// @router /admin/category/add [post]
func (this *CategoryController) AddCategory() {
	var cate models.Category
	var code int

	body := this.Ctx.Input.RequestBody
	//绑定到Category模型
	_ = json.Unmarshal(body,&cate)

	//检查分类是否存在
	code = models.CheckCategory(cate.Name)
	// 分类已存在
	if code == errmsg.ERROR_CATEGORYNAME_USED {
		code = errmsg.ERROR_CATEGORYNAME_USED
	}
	// 分类不存在
	if code == errmsg.SUCCSE {
		// 执行创建新分类
		code = models.CreateCategory(&cate)
	}

	result := map[string]interface{}{
		"status":  code,
		"data":    cate,
		"message": errmsg.GetErrmsg(code),
	}
	this.Data["json"] = result

	this.ServeJSON() //返回json格式
}


//编辑分类
// @router /admin/category/:id [put]
func (this *CategoryController) EditCategory() {
	var cate models.Category
	var code int

	id, _ := this.GetInt(":id")

	body := this.Ctx.Input.RequestBody
	//绑定到Category模型
	_ = json.Unmarshal(body,&cate)

	//检查分类是否存在
	code = models.CheckCategory(cate.Name)
	// 分类已存在
	if code == errmsg.ERROR_CATEGORYNAME_USED {
		code = errmsg.ERROR_CATEGORYNAME_USED
	}
	// 分类不存在
	if code == errmsg.SUCCSE {
		// 执行更新分类
		models.EditCategory(id, &cate)
	}
	result := map[string]interface{}{
		"status":  code,
		"data":    cate,
		"message": errmsg.GetErrmsg(code),
	}
	this.Data["json"] = result

	this.ServeJSON() //返回json格式
}


//删除分类
// @router /admin/catedelete/:id [delete]
func (this *CategoryController) DeleteCategory() {
	id, _ := this.GetInt(":id")

	code := models.DeleteCategory(id)

	result := map[string]interface{}{
		"status":  code,
		"message": errmsg.GetErrmsg(code),
	}
	this.Data["json"] = result

	this.ServeJSON() //返回json格式
}


//获取单个分类
// @router /category/:id [get]
func (this *CategoryController) GetCategory() {
	id, _ := this.GetInt(":id")
	data,code := models.GetCategory(id)

	result := map[string]interface{}{
		"status":  code,
		"data":    data,
		"message": errmsg.GetErrmsg(code),
	}
	this.Data["json"] = result

	this.ServeJSON() //返回json格式
}


//获取分类列表
// @router /categories [get]
func (this *CategoryController) GetCategories() {
	name := this.GetString("name")
	pageSize, err := this.GetInt("pagesize")
	if pageSize < 1 || err != nil{
		pageSize = 5
	}
	pageNum, err := this.GetInt("pagenum")
	if pageNum < 1 || err != nil{
		pageNum = 1
	}

	data, total := models.GetCategories(name,pageSize, pageNum)
	code := errmsg.SUCCSE

	result := map[string]interface{}{
		"status":  code,
		"data":    data,
		"total":   total,
		"message": errmsg.GetErrmsg(code),
	}
	this.Data["json"] = result

	this.ServeJSON() //返回json格式
}


